import React from 'react';
import { connect } from 'dva';
import { createForm } from 'rc-form';
import cx from 'classnames';
import { WingBlank, WhiteSpace, DatePicker, Picker, InputItem, Flex, List, Button, Toast } from 'antd-mobile';
import { Link, routerRedux } from 'dva/router';
import styles from '../scale/styles.less';
import { today, jwData, isbrqData,SCALE_PARTUM } from 'const';

let nowTimeStamp = Date.now();
let now = new Date(nowTimeStamp);
let utcOffset = new Date(now.getTime() - (now.getTimezoneOffset() * 60000));

let minDate = new Date(1900, 1, 1);
let maxDate = now;

Array.prototype.unique2 = function(){
 this.sort(); //先排序
 var res = [this[0]];
 for(var i = 1; i < this.length; i++){
  if(this[i] !== res[res.length - 1]){
   res.push(this[i]);
  }
 }
 return res;
}
function ScalePartumTemplate({ dispatch, location, form, questions, scalevalue , detail, ...rest }) {

  const { state, query } = location;
  const { type, patientid, step, patientvalue, birthday} = location.state;
  const UpdateDate = new Date(birthday).getFullYear();
  const { getFieldProps, getFieldValue, setFieldsValue, validateFields, getFieldError } = form;
  let question = questions[step];

  const updateProductiondate = productiondate => setFieldsValue({ productiondate });

  const isNativeApp = location.pathname.indexOf('/scale_partum') !== -1 && query.s === 'app';

  if (!Object.keys(scalevalue).length) {
    scalevalue = [[], []];
    dispatch({ type: 'scale/save', payload: { scalevalue } });
  }

  let infos = scalevalue[0] || []; //用户信息

  let scores = scalevalue[1] || []; //症状
  
  let nextStep = step + 1;
  const category = step - 2;

  let title = '';
  if (step === 1) {
    title = '完善用户信息';
  }

  let stepQuestions = [];
  if (category >= 0 && category < 6) {
    stepQuestions = SCALE_PARTUM[category].subject;
    title = SCALE_PARTUM[category].title;
  }

  const validateForm = () => {

    validateFields((err, values) => {

      if (err) {
        const fieldNames = Object.keys(err);
        if (fieldNames[0]) {
          return Toast.fail(getFieldError(fieldNames[0]));
        }
      } else {
        if (step === 1) {
          const jw = [];
          for (var i = jwData.length - 1; i >= 0; i--) {
            if (values[jwData[i].id]) {
              jw.push(jwData[i].id);
            }
          }
          if (getFieldValue("hy") < getFieldValue("sc")) {
            setFieldsValue({["hy"]: null});
            setFieldsValue({["sc"]: null});
            return Toast.fail("怀孕次数不得小于生产次数", 1);
          }
          const hy = getFieldValue('hy');// 怀孕次数
          const sc = getFieldValue('sc');// 生产次数
          const brq = typeof(getFieldValue('brq'))=="string"?getFieldValue('brq'):getFieldValue('brq').join(""); // 哺乳期
          const height = getFieldValue('height'); // 身高
          const weight = getFieldValue('weight'); // 体重
          // 国医慧联设定7岁及以上女性, 需要设定一下女性年龄范围
          const production = getFieldValue('production');
          let UpdateBday = production.getFullYear();
          let difference = UpdateBday - UpdateDate;
          if(difference<7){
              setFieldsValue({["production"]: null});
              return Toast.fail("对不起，您选的女性应不小于7岁",1);
          }

          let JWS = jw.reverse(';');
          if (JWS) {
            for (var i = JWS.length - 1; i >= 0; i--) {
              scores.push(JWS[i]);//即往史
            }
          }

          infos = [hy, brq, height, weight, production , sc, jw];
          dispatch({ type: 'scale/save', payload: { scalevalue: [infos, scores] } });
        }
           
        if (step > 1) {
          Object.keys(values).forEach((key) => {

            if (values[key]) {
              scores.push(key);
            } 
          });
        }

        dispatch({ type: 'scale/save', payload: { scalevalue: [infos, scores] } });

        if (nextStep <= 7) {
          let pathname = location.pathname;

          if (isNativeApp) {
            pathname = `${location.pathname}?s=${query.s}&doctorid=${query.doctorid}&memberid=${query.memberid}`;
            
          }
          dispatch(
            routerRedux.replace({
              pathname,
              state: {
                type,
                patientid,
                step: nextStep,
              },
            }),
          );
        } else {
          // 最后一页'提交'
          scores = scores.unique2();
          if(scores.length <= 3){
            Toast.fail('选择的症状信息过少，请重新选择');
    
          }else if(scores.length > 3){

              // 提交的时候注意的特殊几个需要传的,以下都是需要在测评量表里 scores单独添加的。
              let lactation = "1";
              if( infos[1]== 1){
                  scores.push(lactation);//哺乳期
              }
              let pregnant = "4";
              if(infos[0] >=6){
                  scores.push(pregnant);//怀孕次数
              }
              
              let BWI = infos[3]/infos[2];
              let baric_index = "5";
              if (BWI<18.5){
                  scores.push(baric_index);//体重指数BMI
              }
              infos[4]  = infos[4].getFullYear() + '/' + (infos[4].getMonth() + 1) + '/' + infos[4].getDate() + ' '+ today[infos[4].getDay()] + ' ' + infos[4].getHours() + ':' + infos[4].getMinutes() + ':' + infos[4].getSeconds();
              const patientValue = `${infos[0]}|${infos[1]}|${infos[2]}|${infos[3]}|${infos[4]}|${scores.join(';')}`;
      
              dispatch({
                type: 'scale/submitQuestions',
                payload: {
                  type: 'partum',
                  patientId: state.patientid,
                  familyId: JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId,
                  patientValue,
                  jw: infos[6].join(';'), 
                  sc: infos[5],
                  ...rest,
                },
              });
            }
        }
      }
    });
  };

  function isDisable(name, value, i){
      if(getFieldValue(36) && name == 38 || getFieldValue(38) && name == 36){
        return true;
      }
     
      if (scalevalue[1] && scalevalue[1].indexOf("36")!= -1 && name == 38) {
          return true;
      }
      if (scalevalue[1] && scalevalue[1].indexOf("38")!= -1 && name == 36) {
          return true;
      }

      if(getFieldValue(36) && name == 39 || getFieldValue(39) && name == 36){
        return true;
      }
    
      if (scalevalue[1] && scalevalue[1].indexOf("36")!= -1 && name == 39) {
          return true;
      }
      if (scalevalue[1] && scalevalue[1].indexOf("39")!= -1 && name == 36) {
          return true;
      }

      if(getFieldValue(6) && name == 7 || getFieldValue(7) && name == 6){
        return true;
      }
      
      if (scalevalue[1] && scalevalue[1].indexOf("6")!= -1 && name == 7) {
          return true;
      }
      if (scalevalue[1] && scalevalue[1].indexOf("7")!= -1 && name == 6) {
          return true;
      }


      if(getFieldValue(10) && name == 11 || getFieldValue(11) && name == 10){
        return true;
      }
      
      if (scalevalue[1] && scalevalue[1].indexOf("10")!= -1 && name == 11) {
          return true;
      }
      if (scalevalue[1] && scalevalue[1].indexOf("11")!= -1 && name == 10) {
          return true;
      }


      if(getFieldValue(114) && name == 115 || getFieldValue(115) && name == 114){
        return true;
      }
      
      if (scalevalue[1] && scalevalue[1].indexOf("114")!= -1 && name == 115) {
          return true;
      }
      if (scalevalue[1] && scalevalue[1].indexOf("115")!= -1 && name == 114) {
          return true;
      }
      return false;
  }

  function isActive(key, value, i) {
      if (Array.from(scores).find(item => item === key)) {
        return true;
      }

      if (!getFieldValue(key)) {
        return false;
      }

      return getFieldValue(key) === value;
  }

  function handleChange({ target: { type, name, value } }) {
      if (Array.from(scores).find(item => item === name)) {
        setFieldsValue({ [name]: value }); //form实际值与状态不符，用赋值保持相符
        scores = Array.from(scores).filter(item => item !== name); //从scores中去除
      }
      if (getFieldValue(name) === value) {
          setFieldsValue({ [name]: null });
      } else {
          setFieldsValue({ [name]: value });
      }
      if(getFieldValue(36) && name == 38 || getFieldValue(38) && name == 36){
          setFieldsValue({ [name]: null });
      }
     
      if (scalevalue[1] && scalevalue[1].indexOf("36")!= -1 && name == 38) {
          setFieldsValue({ [name]: null });
      }
      if (scalevalue[1] && scalevalue[1].indexOf("38")!= -1 && name == 36) {
          setFieldsValue({ [name]: null });
      }

      if(getFieldValue(36) && name == 39 || getFieldValue(39) && name == 36){
          setFieldsValue({ [name]: null });
      }
    
      if (scalevalue[1] && scalevalue[1].indexOf("36")!= -1 && name == 39) {
          setFieldsValue({ [name]: null });
      }
      if (scalevalue[1] && scalevalue[1].indexOf("39")!= -1 && name == 36) {
          setFieldsValue({ [name]: null });
      }

      if(getFieldValue(6) && name == 7 || getFieldValue(7) && name == 6){
          setFieldsValue({ [name]: null });
      }
      
      if (scalevalue[1] && scalevalue[1].indexOf("6")!= -1 && name == 7) {
          setFieldsValue({ [name]: null });
      }
      if (scalevalue[1] && scalevalue[1].indexOf("7")!= -1 && name == 6) {
          setFieldsValue({ [name]: null });
      }

      if(getFieldValue(10) && name == 11 || getFieldValue(11) && name == 10){
          setFieldsValue({ [name]: null });
      }
      
      if (scalevalue[1] && scalevalue[1].indexOf("10")!= -1 && name == 11) {
          setFieldsValue({ [name]: null });
      }
      if (scalevalue[1] && scalevalue[1].indexOf("11")!= -1 && name == 10) {
          setFieldsValue({ [name]: null });
      }

      if(getFieldValue(114) && name == 115 || getFieldValue(115) && name == 114){
          setFieldsValue({ [name]: null });
      }
      
      if (scalevalue[1] && scalevalue[1].indexOf("114")!= -1 && name == 115) {
          setFieldsValue({ [name]: null });
      }
      if (scalevalue[1] && scalevalue[1].indexOf("115")!= -1 && name == 114) {
          setFieldsValue({ [name]: null });
      }
      dispatch({ type: 'scale/save', payload: { scalevalue: [infos, scores] } });           
  }

  function nextHandler() {
    window.scrollTo(0, 0);
    nextStep = step + 1;
    validateForm();
  }

  function prevHandler() {
    window.scrollTo(0, 0);
    nextStep = step - 1;
    validateForm();
  }
  
  function submitHandler() {
    nextStep = step + 1;
    validateForm();
  }
  function isBlur(type,value){
    if (type == "height") {
      if (value < 0 || value > 300) {
        setFieldsValue({[type]: null});
        return Toast.fail("请输入正确的身高0~300cm！", 1);
      }
    }
    if (type == "weight") {
      if (value < 20 || value > 200) {
        setFieldsValue({[type]: null});
        return Toast.fail("请输入正确的体重20~200kg！", 1);
      }
    }
    if (type == "hy") {
      if (value <1) {
        // 之前是需要判断1-4次, 因为产后症状对应表的原因。
        setFieldsValue({[type]: null});
        return Toast.fail("请输入正确的怀孕次数1次以上！", 1);
      }
    }
    if (type == "sc") {
      if (value <1) {
        setFieldsValue({[type]: null});
        return Toast.fail("生产次数大于等于1并小于等于怀孕次数", 1);
      }
    }
  }

  return (
    <WingBlank size="md">
      <WhiteSpace />
      <List>
        <List.Item>
          <Flex justify="center">{`${step}/7 ${title || detail.Title}`}</Flex>
          {step!==1?
            <div>
            <Flex justify="center" style={{marginTop: '0.1rem'}}>您近期（1-2个月）是否出现以下症状</Flex>
            <Flex justify="center">（有即选，无则不选，可以多选）</Flex>
            </div>:""}
        </List.Item>
        {step === 1
          ? /*第1页自定义表单*/
            <div>
              <InputItem
                {...getFieldProps('height', {
                  initialValue: infos[2] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入身高' }],
                    },
                  ],
                  normalize:(v, prev) => {
                    if (v && !/^(([1-9]\d*)|0)(\.\d{0,1}?)?$/.test(v)) {
                      if (v === '.') {
                        return '0.';
                      }
                      return prev;
                    }
                    return v;
                  },
                })}
                placeholder="请输入身高"
                type="digit" 
                onBlur={() => isBlur("height",getFieldValue('height'))}
              >
                身高(cm)
              </InputItem>
               <InputItem
                {...getFieldProps('weight', {
                  initialValue: infos[3] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入体重' }],
                    },
                  ],
                  normalize:(v, prev) => {
                    if (v && !/^(([1-9]\d*)|0)(\.\d{0,1}?)?$/.test(v)) {
                      if (v === '.') {
                        return '0.';
                      }
                      return prev;
                    }
                    return v;
                  },
                })}
                placeholder="请输入体重"
                type="digit" 
                onBlur={() => isBlur("weight",getFieldValue('weight'))}
              >
                体重(kg)
              </InputItem>
                <InputItem
                {...getFieldProps('hy', {
                  initialValue: infos[0] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入怀孕次数' }],
                    },
                  ],
                })}
                placeholder="请输入怀孕次数"
                type="number"
                onBlur={() => isBlur("hy",getFieldValue('hy'))}
              >
                怀孕次数
              </InputItem>
              <InputItem
                {...getFieldProps('sc', {
                  initialValue: infos[5] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入生产次数' }],
                    },
                  ],
                })}
                placeholder="请输入生产次数"
                type="number"
                onBlur={() => isBlur("sc",getFieldValue('sc'))}
              >
                生产次数
              </InputItem>
              <DatePicker
                {...getFieldProps('production', {
                  initialValue: infos[4] || '',
                  validate: [{
                    trigger: false,
                    rules: [{ required: true, message: '请选择生产日期' }],
                  }],
                })}
                mode="date"
                title="请选择"
                minDate={minDate}
                maxDate={maxDate}
              >
                <List.Item arrow="horizontal">生产日期</List.Item>
              </DatePicker>
              <Picker
                data={isbrqData}
                {...getFieldProps('brq', {
                  initialValue: infos[1] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请选择是／不是' }],
                    },
                  ],
                })}
              >
                <List.Item arrow="horizontal">哺乳期</List.Item>
              </Picker>
              <List.Item key="jw">
                既往史
                <List.Item.Brief>
                  <Flex wrap="wrap" className={styles.questionOptions}>
                    {jwData.map((option, i) => {
                      const key = option.id;
                      const value = option.label;
                      return (
                        <label key={key} className={cx(styles.questionOption, styles.questionOptionNormal, { [styles.questionOptionActive]: isActive(key, value, i) })}>
                          <input {...getFieldProps(`${key}`)} type="checkbox" name={key} value={value} checked={isActive(key, value, i)} onChange={handleChange} />
                          {value}
                        </label>
                      );
                    })}
                  </Flex>
                </List.Item.Brief>
              </List.Item>
            </div>
            : /*第2-7页动态题目*/
            stepQuestions.map((question, i) => (
              <List.Item wrap multipleLine key={question.id}>
                {`${i + 1}. ${question.title}`}
                <List.Item.Brief>
                  <Flex wrap="wrap" className={styles.questionOptions}>
                    {question.item.map((option, i) => {
                      const key = option.id;
                      const value = option.title;
                      return (
                        <label 
                          key={key} className={cx(styles.questionOption, styles.questionOptionNormal, { 
                            [styles.questionOptionActive]: isActive(key, value, i),
                            [styles.questionOptionDisable]: isDisable(key, value, i), })}>
                          <input {...getFieldProps(`${key}`)} type="checkbox" name={key} value={value} checked={isActive(key, value, i)} onChange={handleChange} />
                          {value}
                        </label>
                      );
                    })}
                  </Flex>
                </List.Item.Brief>
              </List.Item>
            ))}
        <div>
          <WhiteSpace size="xl" />
          <WingBlank>
            <Flex>
              {step === 1
                ? null
                : <Flex.Item>
                  <Button onClick={prevHandler}>上一页</Button>
                </Flex.Item>}

              {step < 7 
                ? <Flex.Item>
                  <Button type="primary" onClick={nextHandler}>下一页</Button>
                </Flex.Item>
                : <Flex.Item>
                  <Button type="primary" onClick={submitHandler}>提交</Button>
                </Flex.Item>}

            </Flex>
          </WingBlank>
          <WhiteSpace size="xl" />
        </div>
      </List>
      <WhiteSpace size="xl" />
    </WingBlank>
  );
}

export default connect(({ scale }) => ({ ...scale }))(createForm()(ScalePartumTemplate));
